package org.afox.util;

import java.io.*;
import java.util.*;
//import java.util.regex.*;

public class ClassCollector
{
	static final int SUFFIX_LENGTH = ".class".length();

	public ClassCollector()
	{
	}
	
	public Iterator collectClasses()
	{
		return collectClasses(null);
	}

	public Iterator collectClasses(String match)
	{
		String classPath = System.getProperty("java.class.path");
		HashMap result = collectFilesInPath(classPath, match);
		return result.values().iterator();
	}
	
	public HashMap collectFilesInPath(String classPath, String match)
	{
		HashMap result = collectFilesInRoots(splitClassPath(classPath), match);
		return result;
	}
	
	private HashMap collectFilesInRoots(Vector roots, String match)
	{
		HashMap result = new HashMap();
		Iterator it = roots.iterator();
		while (it.hasNext())
		{
			gatherFiles(new File((String)it.next()), "", result, match);
		}
		return result;
	}
	
	private void gatherFiles(File classRoot, String classFileName, HashMap result, String match)
	{
		//		System.out.println("ClassRoot |" + classRoot+"|");
		//		System.out.println("ClassNameFromFile |" + classFileName+"|");

		File thisRoot = new File(classRoot, classFileName);
		if(thisRoot.isFile() && classFileName.endsWith(".class"))
		{
			String className = classNameFromFile(classFileName);
			if (match!=null)
			{
				if (className.matches(match))
					result.put(className, className);
			}
			else
				result.put(className, className);
			return;
		}

		String contents[] = thisRoot.list();
		if(contents != null)
		{
			for(int i = 0; i < contents.length; i++)
				gatherFiles(classRoot, classFileName + File.separatorChar + contents[i], result, match);
			
		}
	}
	
	private Vector splitClassPath(String classPath)
	{
		Vector result = new Vector();
		StringTokenizer tokenizer = new StringTokenizer(classPath, System.getProperty("path.separator"));

		while(tokenizer.hasMoreTokens())
		{
			result.addElement(tokenizer.nextToken());
		}
		return result;
	}
	
	protected String classNameFromFile(String classFileName)
	{
		String s = classFileName.substring(0, classFileName.length() - SUFFIX_LENGTH);
		String s2 = s.replace(File.separatorChar, '.');
		if(s2.startsWith("."))
			return s2.substring(1);
		else
			return s2;
	}
	
	
}
